<template>
  <div class="app-container calendar-list-container">
      <!-- 搜索框，对工单单号,工单单别进行搜索 -->
    <div class="filter-container">
        <!-- style="width: 150px;margin-right:15px;margin-top:7px" -->
      <el-input
            clearable
            v-model="listQuery.workOrderNo"
            style="margin-right: 15px;margin-top:7px"
            :style="{ width: inputWid(listQuery.workOrderNo) }"
            class="filter-item"
            placeholder="请输入工单单号"
      ></el-input>
      <el-input
            clearable
            v-model="listQuery.orderType"
            style="width: 150px;margin-right:15px;margin-top:7px"
            class="filter-item"
            placeholder="请输入工单单别"
      ></el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
    </div>


    <!-- 工单信息列表 -->
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="medium">
            <el-form-item label="是否临技" v-if="this.form.workCenter && this.form.workCenter.includes('EMS总装车间')">
                <el-input placeholder="临技条码" v-model="deviceDarcodeLinJi" style="width:300px" :disabled="protech=='0'?false:true">
                    <el-switch slot="prepend" v-model="protech" @change="changeprotech" active-value="1" inactive-value="0" active-text="是" inactive-text="否" />
                </el-input>
            </el-form-item>
            <el-form-item label="工单单号" prop="workOrderNo" >
                <el-input v-model="form.workOrderNo" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="工单单别" prop="orderType">
                <el-input v-model="form.orderType" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="任务令" prop="po">
                <el-input v-model="form.po" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="工段编号" prop="sectionNo" required>
                <el-input v-model="form.sectionNo" @blur="checkSectionExist" style="width:300px" />
                <!-- <el-select v-model="form.sectionNo" placeholder="请选择工段编号" @focus="getSection" style="width:300px">
                    <el-option :value="item" :label="item" v-for="(item,index) in this.sectionList" :key="index"/>
                </el-select> -->
            </el-form-item>
            <el-form-item label="排产时间" prop="planTime" required>
                <el-date-picker v-model="form.planTime"  format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" style="width:300px" />
            </el-form-item>
            <el-form-item label="排产数量" prop="planNumber" required>
                <el-input v-model.number="form.planNumber" type="number" style="width:300px"/>
            </el-form-item>
            <el-form-item label="剩余可排产数量" prop="surplusAmount">
                <el-input v-model="form.surplusAmount" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="预计产量" prop="estimateYield">
                <el-input v-model="form.estimateYield" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="BOM时间" prop="bomTimeStr">
                <el-input v-model="form.bomTimeStr" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="BOM版本" prop="bomVersion">
                <el-input v-model="form.bomVersion" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="非标信息" prop="notStandard">
                <el-input v-model="form.notStandard" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="免检信息" prop="exemption">
                <el-input v-model="form.exemption" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="预计开始时间" prop="estimateStartTimeStr">
                <el-input v-model="form.estimateStartTimeStr" style="width:300px"  disabled/>
            </el-form-item>
            <el-form-item label="预计结束时间" prop="estimateEndTimeStr" required>
                <!-- <el-input v-model="form.estimateEndTimeStr" style="width:300px"/> -->
                <el-date-picker
                v-model="form.estimateEndTimeStr"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择预计结束时间"
                style="width:300px">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="工作中心" prop="workCenter">
                <el-input v-model="form.workCenter" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="产品品号" prop="produceNo">
                <el-input v-model="form.produceNo" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="客户编码" prop="clientNumber">
                <el-input v-model="form.clientNumber" style="width:300px" />
            </el-form-item>
            <el-form-item label="产品名称" prop="produceName">
                <el-input v-model="form.produceName" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="产品规格" prop="specification">
                <el-input v-model="form.specification" style="width:300px" disabled />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :loading="formLoading" @click="submitForm('form')">添加</el-button>
                <el-button type="primary" @click="resetForm('form')">重置</el-button>
            </el-form-item>
        </el-form>
  </div>
</template>

<script>
import { orderInfo, addOrderPlan, getSectionList,findLinJi,saveLinJi,delLinJi } from '../../api/productionPlan'
import { getProcessList,saveLinJiPro } from '../../api/processRoute'
import { WorkSecExist,checkWorkSecInfo } from '../../api/workSection.js'
export default {
    name: 'add_Plan',
    data() {
        const validatePlanNumber = (rules,value, callback) => {
            if(value === '') {
                callback(new Error('请输入合适排产数量'))
            } else if (value<0) {
                callback(new Error('排产数量不能为负数'))
            } else {
                callback()
            }
        }
        return {
            listQuery: {
                workOrderNo: '',						//工单单号
                orderType: ''							//工单单别
            },
            // 产品信息表单，需提交后台
            form: {
                workOrderNo: '',						//工单单号
                orderType: '',							//工单单别
                sectionNo: '',							//工段编号
                planNumber: '',							//排产数量
                planTime: '',							//排产时间
                bomTimeStr: '',							//BOM时间
                bomVersion: '',							//BOM版本
                notStandard: '',						//非标信息
                estimateStartTimeStr: '',				//预计开始时间
                estimateEndTimeStr: '',					//预计结束时间
                estimateYield: '',						//预计产量
                workCenter: '',							//工作中心
                produceName: '',						//产品名称
                specification: '',						//产品规格
                surplusAmount: '',						//剩余可排产数量
                exemption: ''							//免检标志位
            },
            sectionList: null,							//已经录入后台的工段编号
            rules: {
                planTime: [{required: true, message: '请选择排产时间', trigger: 'blur' }],
                // {required: true, message: '请输入合适排产数量', trigger: 'blur' }
                planNumber: [{ required: true, trigger: 'blur', validator: validatePlanNumber}],
                sectionNo: [{required: true, message: '请选择相应工段编号', trigger: 'blur' }],
                estimateEndTimeStr: [{required: true, message: '请选择预计结束时间', trigger: 'blur' }],
            },
            protech: '',
            deviceDarcodeLinJi: '',
            optionsProcess: {},
            formLoading: false
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        // 输入工单单号与工单单别，查询相应的数据
        async handleFilter() {
            if (this.listQuery.workOrderNo == '') return this.$message({
                message: '工单单号不能为空',
                type: 'warning'
            })
            if (this.listQuery.orderType == '') return this.$message({
                message: '工单单别不能为空',
                type: 'warning'
            })
            let query = Object.assign({},this.listQuery)
            query.lineType = '2'
            let data = await orderInfo(query)
            if(data.code == '500') return console.log(data.msg)
            this.form = Object.assign({},data.data)
            if(!this.form.clientNumber) this.$message.error('该工单客户品号为空，无法添加！')
            this.form.notStandard = (this.form.notStandard == 'N') ? '标准' : '非标'
            this.form.exemption = (this.form.exemption == '0')  ? '免检' : '非免检'
            this.form.estimateEndTimeStr = ''
            await this.findLinJi()
            this.optionsProcess = {}
            await this.getProcessList()
            // if(this.form.workCenter && this.form.workCenter.includes('EMS总装车间') || this.form.workCenter.trim() == '焊喷车间') {
            //     this.optionsProcess = {}
            //     await this.getProcessList()
            // }
            if(this.form.workCenter == '喷涂车间'){
              this.form.sectionNo = '020302'
            }
        },
        // 提交表单之前先进行验证
        submitForm(formName) {
            this.$refs[formName].validate(async(valid) => {
                if (valid) {
                    if(!this.form.workCenter) return this.$message.error('工作中心为空！')
                    if(this.form.workCenter.trim() == '装配车间' || this.form.workCenter.trim() == 'EMS总装车间'){
                        if(!this.form.clientNumber) return this.$message.error('该工单客户品号为空，无法添加！')
                    }
                    await this.getProcessList()
                    await this.intercept()
                } else {
                    return false
                }
            })
        },
        // 拦截，提示把剩余可排产全部排完，不排完不会继续拦截
        intercept(value){
            if(this.form.surplusAmount!='0' && this.form.surplusAmount > this.form.planNumber) return this.$confirm('请把剩余可排产全部排完', '注意', {
                confirmButtonText: '继续添加',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.onSubmit()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
            this.onSubmit()
        },
        // 将工单信息表单提交到后台
        async onSubmit(value) {
            let query = Object.assign({},this.form)
            query.planTime = query.planTime.split(' ')[0]
            if(query.estimateEndTimeStr < query.planTime) return this.$message.warning('结束时间不能比排产时间早！')
            query.estimateEndTimeStr = query.estimateEndTimeStr.split('-')[0] + query.estimateEndTimeStr.split('-')[1] + query.estimateEndTimeStr.split('-')[2]
            this.formLoading = true
            query.notStandard = (query.notStandard == '标准') ? 'N' : 'Y'
            query.exemption = (query.exemption == '免检') ? '0' : '1'
            if(this.form.clientNumber){ query.clientNumber = this.form.clientNumber.trim() }
            if(this.form.orderPlanNo){ query.orderPlanNo = this.form.orderPlanNo.trim() }
            const data = await addOrderPlan(query)
            this.formLoading = false
            const errMsg = data.msg
            if(data.code == '1'){
                this.handleFilter()
                this.$message({
                	message: '添加成功',
                	type: 'success'
              	})
         	} else {
              	this.$message({
                	message: data.msg,
                	type: 'warning'
              	})
            }
        },
        // 工段编号sectionNo下拉触发函数
        async getSection() {
            const data = await getSectionList()
            this.sectionList = data.data
        },
        // 查询创建的临技
        async findLinJi() {
            let query = {
                WorkOrderNo: this.listQuery.workOrderNo,
                OrderType: this.listQuery.orderType
            }
            const {data} = await findLinJi(query)
            console.log('查询创建的临技',data)
            if(data){
                this.protech = data.deviceDarcodeLinJi?'1':'0'
                this.deviceDarcodeLinJi = data?data.deviceDarcodeLinJi:''
            }
        },
        changeprotech(e){
            if(!this.form.workOrderNo){
                this.$message({
                    message: '请先输入工单号查询',
                    type: 'warning'
                })
                this.protech = ''
                return
            }
            if(e == '1'){
                if(!this.deviceDarcodeLinJi){
                    this.$message({
                        message: '临技条码不能为空',
                        type: 'warning'
                    })
                    this.protech = '0'
                    return
                }
                this.saveLinJi()
            } else if(e == '0'){
                this.delLinJi()
            }
        },
        // 获取工序
        async getProcessList(){
                let query = {
                    technologyNo: this.form.produceNo,
                    technologyEnd: this.form.produceNo,
                    page: 1,
                    limit: 1000
                }
                const data = await getProcessList(query)
                if(data.code != '1') return this.$message.error(data.msg)
                if(!data.data.records.length){
                    this.form = {}
                    return this.$message.error('该工单未添加工艺信息!')
                } else if(this.form.workCenter.trim() == '焊喷车间'){
                    this.form.workCenter = data.data.records[0].workCenter
                    if(data.data.records[0].workCenter == '喷涂车间'){
                      this.form.sectionNo = '020302'
                    }
                }else {
                    this.optionsProcess = data.data.records[0]
                }

        },
        // 计划排产创建临技 
        async saveLinJi() {
            let query = {
                deviceDarcodeLinJi: this.deviceDarcodeLinJi,
                WorkOrderNo: this.listQuery.workOrderNo,
                OrderType: this.listQuery.orderType
            }
            const data = await saveLinJi(query)
            if(data.code == '1'){
                this.saveprotech()
                // this.$message({
                //     message: data.msg,
                //     type: 'success'
                // })
            } else {
                this.protech = '0'
                this.$message({
                    message: data.msg,
                    type: 'error'
                })
            }
        },
        // 工艺指定那个工序需要临技校验
        async saveprotech(){
              let query = {
                    processOrder: this.optionsProcess.processOrder,
                    OrderType: this.form.orderType,
                    WorkOrderNo: this.form.workOrderNo
              }
              const data = await saveLinJiPro(query)
              if(data.code == '1'){
                    this.$message.success(data.msg)
              } else {
                this.$message.error(data.msg)
                this.protech = '0'
              }
        },
        // 删除创建的临技
        async delLinJi() {
            let query = {
                WorkOrderNo: this.listQuery.workOrderNo,
                OrderType: this.listQuery.orderType
            }
            const data = await delLinJi(query)
            if(data.code == '1'){
                this.$message({
                    message: '删除成功！',
                    type: 'success'
                })
            } else {
                this.$message({
                    message: data.msg,
                    type: 'error'
                })
            }
        },
        // 对整个表单输入进去清空
        resetForm(formItem) {
          this.$refs[formItem].resetFields()
        },
        // 当焦点移开input输入框触发该函数，检查工段编号是否已经注册
        async checkSectionExist() {
            if(!this.form.sectionNo) return this.$message.error('工段编号不能为空')
            const data = await checkWorkSecInfo({sectionId: this.form.sectionNo})
            let errormsg = data.msg
            if(data.code =='500') return
            if(data.code =='1' && data.data.records.length){
                this.$message({
                    type: 'success',
                    message: '工段编号验证通过!'
                })
            } else if(data.code =='1' && !data.data.records.length){
                this.form.sectionNo = ''
                this.$message({
                    type: 'warning',
                    message: '工段编号不存在!'
                })
            } else {
                this.form.sectionNo = ''
                this.$message({
                    type: 'warning',
                    message: errormsg
                })
            }
        },
    }
}
</script>

<style>

</style>
